package com.xiaoshuidi.cloud.module.iot.task;

import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.iot.dal.model.doorLock.DoorLockInfo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbAccountDo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.dal.repository.TbAccountRepository;
import com.xiaoshuidi.cloud.module.iot.enums.BrandEnum;
import com.xiaoshuidi.cloud.module.iot.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.iot.service.DoorLockService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class KunShanHardwareTask {
    private final static Logger LOGGER = LoggerFactory.getLogger(AiKeHardwareTask.class);

    @Autowired
    TbAccountRepository tbAccountRepository;

    @Autowired
    DeviceRepository deviceRepository;
    @Autowired
    DoorLockService doorLockService;
    @XxlJob("iot-kunshan-doorLock-task")
    @TenantIgnore
    public void refreshKunShanHardware() {
        List<TbAccountDo> kunShanTb = tbAccountRepository.getApiListByBrandNo(BrandEnum.KUNSHAN.getBrand());
        for (TbAccountDo tbAccountDo : kunShanTb) {
            String apiNo = tbAccountDo.getApiNo();
            //查询该tb_account下挂的所有设备
            List<TbDeviceDo> tbDeviceDoList = deviceRepository.getDeviceListByOneApiNo(apiNo);
            //筛选出门锁设备
            List<TbDeviceDo> doorLockList = tbDeviceDoList.stream().filter(tbDeviceDo -> DeviceTypeEnum.DOORLOCK.getCode().equals(tbDeviceDo.getDeviceType())).collect(Collectors.toList());
            for (TbDeviceDo doorLock : doorLockList) {
                ResultModel<DoorLockInfo> doorLockInfoResultModel = null;
                try {
                    doorLockInfoResultModel = doorLockService.refreshDoorLoclInfo(doorLock.getDeviceNo());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                LOGGER.info("Single-定时任务昆山门锁刷新结果:{}", JSONObject.toJSONString(doorLockInfoResultModel));
            }
        }
    }
}
